package com.qys.livesMall.open.mail;


import com.qys.livesMall.open.mail.config.MailConfig;
import com.qys.livesMall.open.mail.modal.MailM;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Slf4j
@Async
public class AmazonSESClient {


    public static void send(MailConfig config, MailM m) throws MessagingException {
        // Create a Properties object to contain connection configuration information.
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", config.getPort());
        props.put("mail.smtp.starttls.enable", config.getStarttlsEnable());
        props.put("mail.smtp.auth", config.getAuth());
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        // Create a Session object to represent a mail session with the specified properties.

        // Create a transport.
        Transport transport = null;
        try {
            Session session = Session.getDefaultInstance(props);
            transport=session.getTransport();
            // Create a message with the specified information.
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(config.getSendUser(), config.getSendName()));
            InternetAddress[] tos = new InternetAddress[m.getToUsers().size()];
            int index=0;
            for(String to:m.getToUsers()){
                tos[index]=new InternetAddress(to);
            }
            msg.setRecipients(Message.RecipientType.TO,tos);
            msg.setSubject(m.getTitle());
            msg.setContent(m.getMsg(), "text/html; charset=UTF-8");
            //msg.setText(m.getMsg(), "utf-8", "html");




            // Send the message.
            System.out.println("Sending...");

            // Connect to Amazon SES using the SMTP username and password you specified above.
            transport.connect(config.getHost(), config.getUserName(), config.getPassword());

            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        } catch (Exception ex) {
            System.out.println("The email was not sent.");
            System.out.println("Error message: " + ex.getMessage());
        } finally {
            // Close and terminate the connection.
            transport.close();
        }
    }

    public static void main(String[] args) throws Exception {




    }
}
